from django.shortcuts import render
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from .models import a_aduit_data, a_items, a_rules, a_user_rule
from datetime import datetime
from django.db import connection, transaction
from django.db.models import Q
from django.core.cache import cache
from .tools.w_jenkinsapi import Jenkins_build
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
import json
import time
# Create your views here.
#流程审核
@login_required(login_url='/login')
def myaudit(request):
    username = request.user
    rule_level = list(a_user_rule.objects.filter(is_delete=0, username=username).values_list('rule_id'))
    aduit_my = []
    aduit_on = []
    rule_data = []
    item_data = []
    if rule_level == []:
        return_rule_level = -1
    else:
        return_rule_level = rule_level[0][0]
        aduit_my, aduit_on, rule_data, item_data = sel_data(return_rule_level)
        print(aduit_my)
    return render(request, 'audit/myaudit.html', {"rule_level": return_rule_level, "aduit_my":aduit_my,"aduit_on":aduit_on,"rule_data":json.dumps(rule_data),"item_data":item_data})

@csrf_exempt
@login_required(login_url='/login')
def auditadd(request):
    if request.is_ajax():
        if request.method == "POST":
            data = request.POST.dict()
            nel_date = datetime.now()
            data["completeDate"] = nel_date
            a_aduit_data.objects.create(**data)
            return HttpResponse(json.dumps({"status": 0}))

@csrf_exempt
@login_required(login_url='/login')
def auditaddpro(request):
    if request.is_ajax():
        if request.method == "POST":
            _status = 1
            try:
                data = request.POST.dict()
                nel_date = datetime.now()
                data["completeDate"] = nel_date
                aid = data.pop("id")
                a_aduit_data.objects.filter(id=aid).update(**data)
                _status = 0
            except BaseException as b:
                _log_err = "auditaddpro 函数报错 -->" + str(b)
                print(_log_err)
            finally:
                return HttpResponse(json.dumps({"status": _status}))

@csrf_exempt
@login_required(login_url='/login')
def auditobtain(request):
    if request.is_ajax():
        if request.method == "POST":
            data = int(request.POST.get("level"))
            aduit_my, aduit_on, rule_data, item_data = sel_data(data)
            return HttpResponse(json.dumps({"aduit_my": aduit_my, "aduit_on": aduit_on, "rule_data": json.dumps(rule_data), "item_data": item_data}))

@csrf_exempt
@login_required(login_url='/login')
def auditthrough(request):
    if request.is_ajax():
        if request.method == "POST":
            _status = 1
            try:
                data = request.POST.dict()
                nel_date = datetime.now()
                data["completeDate"] = nel_date
                print(data)
                aid = data.pop("id")
                a_aduit_data.objects.filter(id=aid).update(**data)
                _status = 0
            except BaseException as b:
                _log_err = "auditthrough 函数报错 -->" + str(b)
                print(_log_err)
            finally:
                return HttpResponse(json.dumps({"status": _status}))

@csrf_exempt
@login_required(login_url='/login')
def auditbuild(request):
    if request.is_ajax():
        if request.method == "POST":
            atype = request.POST.get("type")
            if atype == '0':
                aid = request.POST.get("id")
                a_jenkins = Jenkins_build()
                item_list = eval(a_aduit_data.objects.filter(id=aid,is_delete=0).values_list('item_list')[0][0])
                build_list = []
                for i in item_list:
                    item_jenkins = list(a_items.objects.filter(~Q(item_jenkins='0'), item_name=i).values_list("item_jenkins"))
                    if item_jenkins != []:
                        item_name = item_jenkins[0][0]
                        item_name_list = item_name.split(',')
                        if item_name_list[-1] == "":
                            item_name_list.pop()
                        build_list = build_list + item_name_list
                cache.set("build_item_list", build_list)
                print(build_list)
                a_jenkins.Start_thread(build_list)
                return HttpResponse(json.dumps({"status": 0}))
            else:
                jenkins_build_list = cache.get("build_item_list")
                time.sleep(5)
                print(jenkins_build_list)
                a_return_data = {"data": [], "end": 1}
                if jenkins_build_list == None:
                    pass
                else:
                    return_success_data = []
                    for n in jenkins_build_list:
                        build_data = cache.get(n)
                        if build_data != None:
                            return_success_data.append(build_data)
                    print(return_success_data)
                    if len(return_success_data) == len(jenkins_build_list):
                        a_return_data = {"data":return_success_data,"end":1}
                        if return_success_data != []:
                            for x in return_success_data:
                                cache.delete(list(x.keys())[0])
                                print("删除 %s" % x)
                    else:
                        a_return_data = {"data": return_success_data, "end": 0}
                return HttpResponse(json.dumps(a_return_data))

# @csrf_exempt
# def auditrejected(request):
#     if request.is_ajax():
#         if request.method == "POST":
#             _status = 1
#             try:
#                 data = request.POST.dict()
#                 nel_date = datetime.now()
#                 data["completeDate"] = nel_date
#                 aid = data.pop("id")
#                 a_aduit_data.objects.filter(id=aid).update(**data)

def sel_data(uid):
    sel_rule_data = list(a_rules.objects.values_list('rule_name', 'rule_level'))
    sel_rule_json = {}
    for i in sel_rule_data:
        sel_rule_json[i[1]] = i[0]
    sel_item_data = list(a_items.objects.filter(is_delete=0).values_list('item_name', flat=True))
    sel_aduit_sql = """SELECT aa.id, aa.originator, aa.process, ar.rule_name, aa.item_list, aa.item_describe,aa.dismiss_role,aa.dismiss_reason, aa.createDate FROM a_aduit_data aa LEFT JOIN a_rules ar ON aa.process = ar.rule_level WHERE aa.STATUS = 0 AND aa.is_delete = 0"""
    cursor = connection.cursor()  # 获得一个游标(cursor)对象
    cursor.execute(sel_aduit_sql)
    sel_aduit_data = cursor.fetchall()
    sel_aduit_name = [desc[0] for desc in cursor.description]
    sel_aduit_on = []
    sel_aduit_my = []
    for row in sel_aduit_data:
        objDict = {}
        n = 0
        # 把每一行的数据遍历出来放到Dict中
        for index, value in enumerate(row):
            if sel_aduit_name[index] == "dismiss_reason" and value == None:
                value = ""
            objDict[sel_aduit_name[index]] = value
        objDict["createDate"] = objDict["createDate"].strftime("%Y-%m-%d %H:%M:%S")

        if objDict["process"] == uid:
            sel_aduit_my.append(objDict)
        else:
            sel_aduit_on.append(objDict)
    cursor.close()
    return sel_aduit_my, sel_aduit_on, sel_rule_json, sel_item_data


def ahistory(request):
    histroy_sql = """SELECT aa.originator, aa.item_list, aa.item_describe, aa.describe, aa.createDate, aa.completeDate , aa.dismiss_reason, ar.rule_name FROM a_aduit_data aa LEFT JOIN a_rules ar ON aa.dismiss_role = ar.rule_level WHERE aa.status = 1 AND aa.is_delete = 0"""
    return_his_data = histroy_sel(histroy_sql)
    return render(request, 'audit/ahistory.html', {"history_data":return_his_data})


def histroy_sel(histroy_sql):
    cursor = connection.cursor()  # 获得一个游标(cursor)对象
    cursor.execute(histroy_sql)
    sel_his_data = cursor.fetchall()
    sel_his_name = [desc[0] for desc in cursor.description]
    sel_his_on = []
    for row in sel_his_data:
        objDict = {}
        # 把每一行的数据遍历出来放到Dict中
        for index, value in enumerate(row):
            if value == None:
                value = ""
            if sel_his_name[index] == "createDate" or sel_his_name[index] == "completeDate":
                value = value.strftime('%Y-%m-%d %H:%M:%S')

            objDict[sel_his_name[index]] = value
        sel_his_on.append(objDict)
    cursor.close()
    print(sel_his_on)
    return sel_his_on

@csrf_exempt
@login_required(login_url='/login')
def auditdate(request):
    if request.is_ajax():
        if request.method == "POST":
            _status = 1
            return_his_data = []
            try:
                print(request.POST)
                a_type = int(request.POST.get("type"))
                if a_type == 0:
                    date = request.POST.get("date")
                    date_range = date.split(' - ')
                    before_date = date_range[0].replace('-', '')
                    after_date = date_range[1].replace('-', '')
                    histroy_sql = """SELECT aa.originator, aa.item_list, aa.item_describe, aa.describe, aa.createDate, aa.completeDate , aa.dismiss_reason, ar.rule_name FROM a_aduit_data aa LEFT JOIN a_rules ar ON aa.dismiss_role = ar.rule_level WHERE aa.status = 1 AND aa.is_delete = 0 AND DATE_FORMAT(aa.createDate,"%Y%m%d") >= {0} AND DATE_FORMAT(aa.createDate,"%Y%m%d") =< {1}""".format(before_date, after_date)
                    return_his_data = histroy_sel(histroy_sql)
                elif a_type == 1:
                    oname = request.POST.get("name")
                    histroy_sql = """SELECT aa.originator, aa.item_list, aa.item_describe, aa.describe, aa.createDate, aa.completeDate , aa.dismiss_reason, ar.rule_name FROM a_aduit_data aa LEFT JOIN a_rules ar ON aa.dismiss_role = ar.rule_level WHERE aa.status = 1 AND aa.is_delete = 0 AND aa.originator like "%{0}%" """.format(oname)
                    return_his_data = histroy_sel(histroy_sql)
                _status = 0
            except BaseException as b:
                _log_err = "auditdate 函数执行失败 --》" + str(b)
                print(_log_err)
            finally:
                return HttpResponse(json.dumps({"status":_status,"return_his_data":return_his_data}))




def manageconf(request):
    r_user_list, item_list, poor_list, rule_json = manage_sel()
    username = request.user
    rule_level = list(a_user_rule.objects.filter(is_delete=0, username=username).values_list('rule_id'))[0][0]
    return render(request, 'audit/manageconf.html', {"r_user_list":r_user_list, "item_list":item_list, "poor_list":poor_list, "rule_json":rule_json, "rule_level":rule_level})


def dict_sel(sel_d):
    cursor = connection.cursor()  # 获得一个游标(cursor)对象
    cursor.execute(sel_d)
    d_data = cursor.fetchall()
    d_name = [desc[0] for desc in cursor.description]
    d_on = []
    for row in d_data:
        objDict = {}
        # 把每一行的数据遍历出来放到Dict中
        for index, value in enumerate(row):
            objDict[d_name[index]] = value
        objDict["createDate"] = objDict["createDate"].strftime("%Y-%m-%d %H:%M:%S")
        d_on.append(objDict)
    cursor.close()
    return d_on

@csrf_exempt
@login_required(login_url='/login')
def amanageadd(request):
    if request.is_ajax():
        if request.method == "POST":
            _status=3
            r_user_list = []
            item_list = []
            poor_list = []
            rule_json = {}
            try:
                mtype = int(request.POST.get("type"))
                if mtype == 0:
                    mdata = eval(request.POST.get("data"))
                    a_user_rule.objects.create(**mdata)
                    r_user_list, item_list, poor_list, rule_json = manage_sel()
                    _status = 0
                elif mtype == 1:
                    mdata = eval(request.POST.get("data"))
                    mdata["item_jenkins"] = mdata["item_jenkins"] + ','
                    a_items.objects.create(**mdata)
                    r_user_list, item_list, poor_list, rule_json = manage_sel()
                    _status = 1
                else:
                    _status = 2
            except BaseException as b:
                _log_err = "amanageadd 函数异常 --》" + str(b)
                print(_log_err)
            finally:
                return HttpResponse(json.dumps({"status":_status, "r_user_list":r_user_list, "item_list":item_list, "poor_list":poor_list, "rule_json":rule_json}))

@csrf_exempt
@login_required(login_url='/login')
def auditops(request):
    if request.is_ajax():
        if request.method == "POST":
            ops_status = int(request.POST.get("type"))
            db_status = int(request.POST.get("status"))
            _status=0
            if ops_status == 0:
                data = eval(request.POST.get("data"))
                pid = request.POST.get("id")
                print(data)
                if db_status == 0:
                    a_user_rule.objects.filter(id=pid).update(**data)
                else:
                    a_items.objects.filter(id=pid).update(**data)
            else:
                pid = request.POST.get("id")
                if db_status == 0:
                    a_user_rule.objects.filter(id=pid).update(is_delete=1)
                else:
                    a_items.objects.filter(id=pid).update(is_delete=1)
            r_user_list, item_list, poor_list, rule_json = manage_sel()
            return HttpResponse(json.dumps(
                {"status": _status, "r_user_list": r_user_list, "item_list": item_list, "poor_list": poor_list,
                 "rule_json": rule_json}))


def manage_sel():
    rule_user_sel = """select id,username, (select a.rule_name from a_rules a where a.rule_level = rule_id) as rule_name,createDate from a_user_rule where is_delete = 0"""
    item_sel = """select id,item_name,item_jenkins,createDate from a_items where is_delete = 0"""
    rule_user_data = dict_sel(rule_user_sel)
    item_data = dict_sel(item_sel)
    rule_sel = a_rules.objects.values_list('rule_name', 'rule_level')
    user_sel = list(User.objects.filter(is_active=1).values_list('username', flat=True))
    user_r = list(a_user_rule.objects.filter(is_delete=0).values_list('username', flat=True))
    poor_user = [x for x in user_sel if x not in user_r]
    rule_json = {}
    for r_i in rule_sel:
        rule_json[r_i[1]] = r_i[0]
    return rule_user_data, item_data, poor_user, rule_json